package net.topicopedia.servlets.user;
import java.io.IOException;

import javax.servlet.http.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.datastore.Query.CompositeFilterOperator;
import com.google.appengine.api.datastore.Query.Filter;
import com.google.appengine.api.datastore.Query.FilterPredicate;
import com.google.appengine.api.datastore.Query.FilterOperator;

@SuppressWarnings("serial")
public class CreateUserServlet extends HttpServlet {
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		
		String email = req.getParameter("email");
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
		
		Filter emailFilter = new FilterPredicate("email",
				                      FilterOperator.EQUAL,
				                      email);
		
		// Use class Query to assemble a query
		Query userQuery = new Query("User").setFilter(emailFilter);

		// Use PreparedQuery interface to retrieve results
		PreparedQuery pq = datastore.prepare(userQuery);

		resp.addHeader("Access-Control-Allow-Origin", "*");
		resp.setContentType("text/plain");

		for (Entity result : pq.asIterable()) {
		  String storedName = (String) result.getProperty("name");
		  String storedEmail = (String) result.getProperty("email");
		  
		  if ( storedName.equals( name ) && storedEmail.equals( email ) )
		  {
			  resp.getWriter().println( "User exists" );
			  return;
		  }
		}
		
		Entity user = new Entity("User");
		user.setProperty("name", name);
		user.setProperty("email", email);
		user.setProperty("password", password);
		
		Key userKey = datastore.put( user );
		resp.getWriter().println("Hello, " + name + " : " + email + " / " + password );
		resp.getWriter().println(" user id :: " + userKey.getId() );
		
	}
}
 